import { useLocation, Navigate } from 'react-router-dom'
import { getStorage } from '@/utils/storage'
import http from '@/utils/request'
import useuserInfoStore from '@/store/userInfo'
import { useNavigate } from 'react-router-dom'
import { message } from 'antd'

function Private(props: { children: any; }) {
  const localuserInfo = getStorage('user-info')
  const location = useLocation()
  const updateUserInfo = useuserInfoStore((state) => state.updateUserInfo)
  const navigate = useNavigate()

  const getUserInfo = () => {
    http.get('/disp/sys/user/getLoginUserInfo').then((res) => {
      const { userVo } = res.data
      const token = localStorage.getItem('token') || ''
      updateUserInfo({
        ...userVo,
        token
      })
    }).catch(() => {
      message.error('身份已失效，请重新登录', 1).then(() => {
        navigate('/login', { replace: true })
      })
    })
  }

  if (localuserInfo?.token) {
    getUserInfo()
    if (location.pathname === '/') {
      return <Navigate to="/order/order-list" replace />
    }
    return props.children
  } else {
    return <Navigate to={{ pathname: 'login',search: `redircet=${location.pathname}` }} />
  }
}

export default Private